﻿//////////////////////////////////////////////////////////////////////////
// route module
// author   : zhangpeng
// date     : 2012-2-6
// last modified by : zhangpeng
// last update date : 2012-3-20
//////////////////////////////////////////////////////////////////////////
var exec = require("child_process").exec;
var querystring = require("querystring");
var formidable = require('formidable'); 
var fs = require("fs");
var http = require("http");
var util = require("util");
var utilEx = require("./util");
var urlParse = require("url");
var iconv_lite = require("iconv-lite");
var filterHTML = require("./filterHTML");
var path = require("path");

function start(res, req) {
    console.log("request handler 'start' was called.");
    var content = "empty";
    exec("dir", { timeout: 3000, maxBuffer: 20000 * 1024 }, function(error, stdout, stderr) {
        content = stdout;
        res.writeHead(200, { "Content-Type": "text/plain" });
        res.write(content);
        res.end();
    });
}
function startPost(res, req) {
    console.log("request handler 'startPost' was called.");
    var body = "<html>" + 
    "<head>" +
    '<meta http-equiv="Content-Type" content="text/html; ' +
    'charset=UTF-8" />' +
    '</head>' +
    '<body>' +
    '<form action="/upload" method="post">' +
    '<textarea name="text" rows="20" cols="60"></textarea>' +
    '<input type="submit" value="Submit text" />' +
    '</form>' +
    '</body>' +
    '</html>';
    res.writeHead(200, { "Content-Type": "text/html" });
    res.write(body);
    res.end();
}
function index(res, req) {
    var body = '<html>' +
    '<head>' +
    '<meta http-equiv="Content-Type" ' +
    'content="text/html; charset=UTF-8" />' +
    '</head>' +
    '<body>' +
    '<form action="/upload" enctype="multipart/form-data" ' +
    'method="post">' +
    '<input type="file" name="upload">' +
    '<input type="submit" value="Upload file" />' +
    '</form>' +
    '</body>' +
    '</html>';
    res.writeHead(200, { "Content-Type": "text/html" });
    res.write(body);
    res.end();
    fs.writeFile("./logRes.txt", util.inspect(res), "utf8", function(err) {
        if(err) {
            throw err;
        }
    });
    fs.writeFile("./logReq.txt", util.inspect(req), "utf8", function(err) {
        if(err){
            throw err;
        }
    });
}
var globalIndex = 0;
function upload(res, req) {
    console.log("request handler 'upload' was called.");
    var form = new formidable.IncomingForm();
    console.log("about to parse");
    form.parse(req, function(error, fields, files) {
        console.log("parsing done");
        fs.renameSync(files.upload.path, "E:\\node\\demo1\\tmp\\test"+ globalIndex +".png");
        res.writeHead(200, { "Content-Type": "text/html" });
        res.write("received image:<br/>");
        res.write("<img src='/show' />");
        res.end();
    });
}
function show(res, req) {
    fs.readFile("E:\\node\\demo1\\tmp\\test" + globalIndex + ".png", "binary", function(error, file) {
        if (error) {
            res.writeHead(500, { "Content-Type": "text/plain" });
            res.write(error + "\n");
            res.end();
        } else {
            res.writeHead(200, { "Content-Type": "image/png" });
            res.write(file, "binary");
            res.end();
        }
        globalIndex += 1;
    })
}
function agent(res, req) {
    res.writeHead(200, {"Content-Type" : "text/html"});
    res.write("hello world");
    res.end();
}
function staticServer(pathName, res, req) {
    // wwwroot 
    var wwwroot = "E:\webTools";
    var pathObj = urlParse.parse(req.url, true);
    //console.log(util.inspect(pathObj));
    var agentTargetAry = pathObj.pathname.split("/");
    var agentTarget = "www.baidu.com",targetPath = "/";
    if (agentTargetAry.length >= 1) {
        agentTargetAry.shift();
        agentTarget = agentTargetAry.shift();
        targetPath = "/" + agentTargetAry.join("/");
    }
    targetFile = wwwroot + targetPath;
    console.log(targetFile);
    fs.readFile(targetFile, function(err, data){
        if (err) throw err;
        res.writeHead(200, {"Content-Type":"text/html"});
        res.write(data);        
    })
}
function agentKaixin001(pathname, res, req) {
    var pathObj = urlParse.parse(req.url, true);
    //console.log(util.inspect(pathObj));
    var agentTargetAry = pathObj.pathname.split("/");
    var agentTarget = "www.baidu.com",targetPath = "/";
    if (agentTargetAry.length >= 1) {
        agentTargetAry.shift();
        agentTarget = agentTargetAry.shift();
        targetPath = "/" + agentTargetAry.join("/");
    }
    console.log(util.inspect(agentTarget));
    var options = {
        host: agentTarget, //"www.kaixin001.com",
        path: targetPath   //"/repaste/105876543_6264708176.html?uid=3473186&urpid=6374061712"
    };
    http.get(options, function(googlRes){
        //res = googlRes;
        console.log("Got response: \r\n" + "look at the log file");
        //utilEx.WriteLog(googlRes, "./log.txt");
        var content = "" ;
        googlRes.on("data", function(chunk) {
            content += chunk;
            console.log("chunk coming");
            utilEx.WriteLog(chunk, "./log3.txt");
        }).on("end", function(){
            res.writeHead(200, {"Content-Type":"text/html"});
            
            content = filterHTML.ExcludeJSTag(content);
            //content = filterHTML.FetchTagContent(content, "rpstDetail", "div");
            if(content != null) {
                var fetchStr = filterHTML.FetchTagContent(content);
                if (fetchStr == null) {
                    console.log("fetchTagNotDone!!!");
                    res.write(content);
                } else{
                    res.write(fetchStr);                        
                    res.end();
                }            
                res.write(content);                        
                res.end();
            }
        })
        /*
        setTimeout(function(){
            res.writeHead(200, {"Content-Type":"text/html"});
                if(content != null) {
                var fetchStr = filterHTML.FetchTagContent(content);
                if (fetchStr == null) {
                    res.write(content);
                } else{
                    res.write(fetchStr);                        
                    res.end();
                }
            }
        },5000);
        */
    }).on("error", function(e) {
        res.writeHead(200, {"Content-Type":"text/plain"});
        res.write("get error " + e.message);
        res.end();
    })
    /*
    res.writeHead(200, {"Content-Type" : "text/html"});
    res.write("hello kaxin001.com's page 1");
    res.end();
    */
}
function testfs(res, req) {
    // test and study the fs module.
    fs.readFile("./todo.txt", 'utf8',function(err, data) {
        if(err) {
            throw err;
        }
        console.log(data);
    })
    console.log(fs.readFileSync("./todo.txt", "utf8"));
    res.writeHead(200, {"Content-Type" : "text/html"});
    res.write("1 : test readFile " + "\r\nSuccess");
    res.end();
}

var contentTypes = { 
    "aiff" : "audio/x-aiff",
    "arj" : "application/x-arj-compressed",
    "css": "text/css",
  "gif": "image/gif",
  "html": "text/html",
  "ico": "image/x-icon",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "js": "text/javascript",
  "json": "application/json",
  "pdf": "application/pdf",
  "png": "image/png",
  "svg": "image/svg+xml",
  "swf": "application/x-shockwave-flash",
  "tiff": "image/tiff",
  "txt": "text/plain",
  "wav": "audio/x-wav",
  "wma": "audio/x-ms-wma",
  "wmv": "video/x-ms-wmv",
  "xml": "text/xml",
  "json" : "text/plain"
}
function handler404(req, res){
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.write("404 Error");
    res.end();
}
function handler500(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.write("500 Error");
    res.end();

}
function staticPage(pathName, res, req) {
    var root = [];
    //root.push("E:\\jquery_UI_git\\tests\\");
    //root.push("E:\\node\\ebookshare\\e-book-share-platform\\docs\\");
    //root.push("E:\\jquery_UI\\");
    //root.push("E:\\jsgrid-ms\\trunk\\tree_view\\");
    //root.push("E:\\jsgrid-ms\\trunk\\jquery_dev\\");
    //root.push("E:\\webTools\\");
    root.push("D:\\workpath\\manulife\\ManulifeSite\\ManulifeSite\\");
    if (pathName.length > 0) {
        pathName = pathName.slice(1);
    }
    var exists = false;
    for(var i=0; i<root.length; ++i) {
        var curFileName = root[i] + pathName;
        console.log(curFileName);
        if (!exists) {
            var curExists = path.existsSync(curFileName);
            if (!curExists) {
                continue;
            } else{
                fs.readFile(curFileName, "binary", function(err, file) {
                    if (err) {
                        handler500(req, res, err);
                        return;
                    }

                    var ext = path.extname(curFileName);
                    ext = ext ? ext.slice(1) : 'html';
                    res.writeHead(200, { 'Content-Type': contentTypes[ext] || 'text/html' });
                    res.write(file, "binary");
                    res.end();
                });
                exists = true;
            }
        } else{
            break;
        }
    }
    if( !exists ) {
        handler404(req, res);
    }
}

exports.start = start;
exports.upload = upload;
exports.startPost = startPost;
exports.show = show;
exports.index = index;
exports.agent = agent;
exports.agentKaixin001 = agentKaixin001;
exports.testfs = testfs;
exports.staticServer = staticServer;
exports.staticPage = staticPage;